import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javafx.application.Application;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.ResourceBundle;

public class demo {

    //创建c3p0连接池
    @Test
    public void test1() throws Exception {
        //创建数据源
        ComboPooledDataSource dataSource =new ComboPooledDataSource();
        //设置数据连接参数
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUser("root");
        dataSource.setPassword("root");
        //获取连接对象
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
    }

    //创建druid连接池
    @Test
    public void test2() throws Exception{
        //创建数据源
        DruidDataSource druidDataSource =new DruidDataSource();
        //设置数据连接参数
        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql://localhost:3306/test");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("root");
        //获取连接对象
        DruidPooledConnection connection = druidDataSource.getConnection();
        System.out.println(connection);
    }

    //读取jdbc.properties配置文件创建连接池
    @Test
    public void test3() throws Exception {
        //加载类路径下的jdbc.properties
        ResourceBundle rb = ResourceBundle.getBundle("jdbc");
        ComboPooledDataSource dataSource =new ComboPooledDataSource();
        dataSource.setDriverClass(rb.getString("jdbc.driver"));
        dataSource.setJdbcUrl(rb.getString("jdbc.url"));
        dataSource.setUser(rb.getString("jdbc.username"));
        dataSource.setPassword(rb.getString("jdbc.password"));

        Connection connection = dataSource.getConnection();
        System.out.println(connection);
    }

    //测试从容器当中获取数据源
    @Test
    public void test4() throws Exception {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        DataSource dataSource= applicationContext.getBean(DataSource.class);
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
    }
}
